package com.java2404.micro.consumer.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.java2404.micro.common.entity.User;
import com.java2404.micro.consumer.mapper.ConsumerMapper; // 假设你用 MyBatis
import com.java2404.micro.consumer.mapper.UserMapper;
import com.java2404.micro.consumer.service.ConsumerService;
import com.java2404.micro.common.entity.Consumer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

@Service
public class ConsumerServiceImpl extends ServiceImpl<ConsumerMapper, Consumer> implements ConsumerService {

    @Autowired
    private ConsumerMapper consumerMapper;  // 注入 UserMapper 进行数据库操作



    @Override
    public void deductBalance(Integer userId, BigDecimal amount) {
        // 查询消费者
        Consumer consumer = consumerMapper.selectById(userId);
        if (consumer == null) {
            throw new RuntimeException("消费者不存在");
        }

        // 检查余额是否足够
        if (consumer.getBalance() == null || consumer.getBalance().compareTo(amount) < 0) {
            throw new RuntimeException("余额不足");
        }

        // 扣减余额
        BigDecimal newBalance = consumer.getBalance().subtract(amount);
        consumer.setBalance(newBalance);

        // 更新消费者余额
        consumerMapper.updateById(consumer);
    }


}
